import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProviderWidget<T extends ChangeNotifier> extends StatefulWidget {
  ///需要传入的Model
  final T model;

  ///如果Model准备好的回调
  final Function(T model) onModelReady;

  ///不需要刷新的组件
  final Widget? child;

  /// widget的builder
  final ValueWidgetBuilder<T> builder;

  const ProviderWidget(
      {Key? key,
      required this.model,
      required this.onModelReady,
      this.child,
      required this.builder})
      : super(key: key);

  @override
  _ProviderWidgetState createState() => _ProviderWidgetState<T>();
}

class _ProviderWidgetState<T extends ChangeNotifier>
    extends State<ProviderWidget<T>> {
  late T model;

  @override
  void initState() {
    super.initState();
    model = widget.model;
    widget.onModelReady.call(model);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context) => model,
      child: Consumer(
        builder: widget.builder,
        child: widget.child,
      ),
    );
  }
}
